﻿using System.Transactions;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using WebApplication1.API返回类;
using WebApplication1.DTO;
using WebApplication1.Models.商品信息;
using WebApplication1.Models.商品信息.养殖;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// API养殖控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BreedController : ControllerBase
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient _db;
        private readonly ILogger<BreedController> logger;

        public BreedController(IMapper mapper,SqlSugar.ISqlSugarClient db,ILogger<BreedController> logger)
        {
            this.mapper = mapper;
            this._db = db;
            this.logger = logger;
        }


        /// <summary>
        /// 查询养殖表信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public APIResult<List<BreedingModel>> GetBreedAll(int id)
        {
            var list = _db.Queryable<BreedingModel>().Where(x=>x.RId==id).OrderByDescending(x=>x.BreedId);

            return new APIResult<List<BreedingModel>>()
            {
                Code = APIEnum.成功,
                Message = "查询养殖表信息成功",
                Data = list.ToList(),
            };
        }

        /// <summary>
        /// 添加养殖表信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> CreateBreed(BreedDto b)
        {
            BreedingModel model = mapper.Map<BreedingModel>(b);
            int r = _db.Insertable(model).ExecuteReturnIdentity();
            if (r > 0)
            {
                return APIResult<int>.Success("创建养殖数据成功", r);
            }
            else
            {
                return APIResult<int>.Fail("创建养殖数据失败");
            }

        }

        /// <summary>
        /// 修改养殖表信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> UpdateBreed(BreedDto b)
        {
             BreedingModel breeds= _db.Queryable<BreedingModel>().First(x => x.BreedId==b.BreedId);
            if (breeds == null)
            {
                return APIResult<int>.Fail("您要修改的养殖信息不存在");
            }
            BreedingModel model = mapper.Map<BreedingModel>(b);
            int r = _db.Updateable(model).ExecuteCommand();
            if (r > 0)
            {
                return APIResult<int>.Success("修改养殖信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("修改养殖信息失败");
            }

        }

        /// <summary>
        /// 查询免疫信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public APIResult<List<ImmunityModel>> GetImmunityAll(int id)
        {
            var list = _db.Queryable<ImmunityModel>().Where(x => x.RId == id && x.IsDel==false).OrderByDescending(x => x.RId); ;

            return new APIResult<List<ImmunityModel>>()
            {
                Code = APIEnum.成功,
                Message = "查询免疫信息成功",
                Data = list.ToList(),
            };
        }

        /// <summary>
        /// 批量添加免疫信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> CreateImmunityList(int id,List<ImmunityModel> ImmunityList)
        {
            List<ImmunityModel> oldimmunity = _db.Queryable<ImmunityModel>().Where(x => x.RId == id).ToList();
            foreach(var i in oldimmunity)
            {
                i.IsDel = true;
            }
            int r = 0;

            foreach(var i in ImmunityList)
            {
                i.RId = id;
            }
            int r1 = 0;

            //使用事务先批量删除然后批量添加
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    r= _db.Updateable(oldimmunity).ExecuteCommand();//批量逻辑删除
                    r1= _db.Insertable(ImmunityList).ExecuteReturnIdentity();//批量添加
                    tran.Complete();//提交
                }
                catch (Exception e)
                {
                    logger.LogError("批量添加免息信息异常"+e.Message+"已回滚");
                    throw;
                }
            }
            if(r>0 && r1>0)
            {
                return APIResult<int>.Success("保存免疫信息成功",r);
            }
            else
            {
                return APIResult<int>.Fail("保存免疫信息失败");
            }
        }


        /// <summary>
        /// 添加免疫信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> CreateImmunity(ImmunityDto i)
        {
            ImmunityModel model = mapper.Map<ImmunityModel>(i);
            int r = _db.Insertable(model).ExecuteReturnIdentity();//添加免疫信息
            if (r > 0)
            {
                return APIResult<int>.Success("保存免疫信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("保存免疫信息失败");
            }
        }

        /// <summary>
        /// 修改免疫信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> UopdateImmunity(ImmunityDto i)
        {
            ImmunityModel model = mapper.Map<ImmunityModel>(i);
            int r = _db.Updateable(model).ExecuteCommand();//修改免疫信息
            if (r > 0)
            {
                return APIResult<int>.Success("修改免疫信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("修改免疫信息失败");
            }
        }

        /// <summary>
        /// 逻辑删除免疫信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public APIResult<int> DeleteImmunity(int id)
        {
            ImmunityModel model = _db.Queryable<ImmunityModel>().First(x => x.ImmunityId == id);
            if(model==null)
            {
                return APIResult<int>.Fail("您要删除的数据不存在");
            }
            model.IsDel = true;
            int r = _db.Updateable(model).ExecuteCommand();//修改免疫信息
            if (r > 0)
            {
                return APIResult<int>.Success("删除免疫信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("删除免疫信息失败");
            }
        }




    }
}
